package chapter.fifth.item26;

import java.util.Arrays;
import java.util.Collection;

public class GenericStack<E> {
	private E[] elements;
	private int size = 0;
	private static final int DEFAULT_INITIAL_CAPACITY = 16;
	
	@SuppressWarnings("unchecked")
	public GenericStack(){
		elements = (E[])new Object[DEFAULT_INITIAL_CAPACITY];
	}
	
	public void push(E e){
		ensureCapacity();
		elements[size++] = e;
	}

	private void ensureCapacity() {
		if(elements.length==size){
			elements = Arrays.copyOf(elements, 2*size+1);
		}
	}
	
	public E pop() throws IllegalAccessException{
		if(elements.length==0){
			throw new IllegalAccessException();
		}
		//return elements[--size]; 未消除引用，会造成内存泄露
		E e = elements[--size];
		elements[size] = null;
		return e;
	}
	
	//通配符类型服务于E的生产者 PE原则
	public void pushAll(Iterable<? extends E> src){
		for(E e:src)
			push(e);
	}
	
	//通配符类型服务于E的消费者 CS原则
	public void popAll(Collection<? super E> dst) throws IllegalAccessException{
		while(!isEmpty())
			dst.add(pop());
	}
	
	private boolean isEmpty() {
		return size==0;
	}

	public static void main(String[] args) {
		GenericStack<String> stack = new GenericStack<String>();
		stack.push("a");
		stack.push("c");
		try {
			String x = stack.pop();
			System.out.println(x);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
